package com.zhss.dfs.server;

import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @Author liu Weidong
 * @Email:
 * @Date: 2024/5/28 14:53
 * @Version 1.0
 */
public class DelReplicaTask extends Thread {

    private ConcurrentLinkedQueue<String> delTaskQueue;


    public DelReplicaTask() {
        this.delTaskQueue = new ConcurrentLinkedQueue<>();
    }

    @Override
    public void run() {
        while (true) {
            try {
                while (delTaskQueue.isEmpty()) {
                    TimeUnit.MILLISECONDS.sleep(1000);
                }
                String task = delTaskQueue.poll();
                JSONObject jsonObject = JSONObject.parseObject(task);
                String fileName = jsonObject.getString("fileName");
                String absoluteFileName = getAbsoluteFileName(fileName);
                File file = new File(absoluteFileName);
                if (file.exists()) {
                    file.delete();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private String getAbsoluteFileName(String filePath) {
        String parentDir = DataNodeConfig.FILE_DATA +
                filePath.substring(0, filePath.lastIndexOf("/"));
        File file = new File(parentDir);
        if (!file.exists()) {
            file.mkdirs();
        }
        return DataNodeConfig.FILE_DATA + filePath;
    }
}
